package main

import (
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
)

// 编写一个网页程序，可以让用户输入一连串的数字。计算出这些数字的均值和中值，并且打印出来，就像下边这张截图一样：

const Html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Statistics</title>
</head>
<body>
    <h1>Statistics</h1>
	<h3>Computes basic statistcs for given list of numbers</h3>
	<form action="#" method="post" name="statistcs">
		<input type="text" name="numbers">
		<input type="submit" value="Submit">
	</form>
	%s
</body>
</html>
`

const Table = `
<table>
	<tr>
		<th colspan=2>Results</th>
	</tr>
	<tr>
		<th>Numbers</th>
		<td>%v</td>
	</tr>
	<tr>
		<th>Count</th>
		<td>%d</td>
	</tr>
	<tr>
		<th>Mean</th>
		<td>%0.6f</td>
	</tr>
	<tr>
		<th>Median</th>
		<td>%0.6f</td>
	</tr>
</table> 
`

func action(w http.ResponseWriter, r *http.Request) {
	html := ""
	table := ""
	switch r.Method {
	case "GET":
	case "POST":
		numbers := r.FormValue("numbers")
		slice := strings.Fields(numbers)
		numSli := make([]float64, len(slice))
		sum := 0.0
		ix := 0
		count := 0
		mean := 0.0
		median := 0.0

		for _, str := range slice {
			num, err := strconv.ParseFloat(str, 64)
			if err != nil {
				continue
			}
			numSli[ix] = num
			ix += 1
			sum += num
		}
		numSli = numSli[:ix]

		if ix > 0 {
			count = len(numSli)
			mean = sum / float64(count)
			median = numSli[count/2]
		}
		table = fmt.Sprintf(Table, numSli, count, mean, median)
	}
	html = fmt.Sprintf(Html, table)
	io.WriteString(w, html)
}

func main() {
	http.HandleFunc("/", action)
	if err := http.ListenAndServe(":9999", nil); err != nil {
		panic(err)
	}
}
